// 封装组合式功能

import { OrderType } from '@/enums'
import { cancelOrder, followDoctor, getPrescriptionPic } from '@/services/consult'
import type { ConsultOrderItem, FollowType } from '@/types/consult'
import { showImagePreview, showSuccessToast } from 'vant'
import { ref } from 'vue'

// 命名规范 useXxx
// 关注/取消关注组合式功能
export const useFollow = (type: FollowType) => {
  const loading = ref(false)
  const follow = async (item: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true
    try {
      await followDoctor(item.id, type)
      // 手动修改关注数据字段
      item.likeFlag = item.likeFlag === 0 ? 1 : 0
    } finally {
      loading.value = false
    }
  }
  return { loading, follow }
}

// 查看处方组合式功能
export const useShowPrescription = () => {
  const showPrescription = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      // 图片预览
      showImagePreview([res.data.url])
    }
  }
  return { showPrescription }
}

// 取消订单组合式功能
export const useCancelOrder = () => {
  const loading = ref(false)
  const onCancelOrder = async (item: ConsultOrderItem) => {
    try {
      loading.value = true
      await cancelOrder(item.id)
      // 修改订单状态
      item.status = OrderType.ConsultCancel
      // 修改订单状态文字
      item.statusValue = '已取消'
      // 提示用户
      showSuccessToast('取消成功')
    } finally {
      loading.value = false
    }
  }
  return { loading, onCancelOrder }
}
